package com.block.common.util.encrypt;


import org.apache.commons.codec.binary.Hex;

import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;


/**
 * Hmac摘要， 默认HmacSHA256算法
 * Created by mah on 2015/10/28.
 */
public class HmacHanlder {
    public static final String HMACSHA256 = "HmacSHA256";
    public static final String HMACSHA1 = "HmacSHA1";
    public static final String HMACSHA512 = "HmacSHA512";
    public static final String HMACMD5 = "HmacMD5";

    private String macKey;
    private String defaultEncryptType = HMACSHA256;
    private String defaultEncoding = "UTF-8";

    public HmacHanlder(String macKey){
        this.macKey = macKey;
    }

    public HmacHanlder(String macKey, String defaultEncryptType){
        this.macKey = macKey;
        this.defaultEncryptType = defaultEncryptType;
    }

    /**
     * 生成摘要，默认HMACSHA256
     * @param s 明文
     * @return 摘要
     * @throws Exception
     */
    public String encrypt(String s) throws Exception {
        String sign = null;
        try {
            Mac mac = Mac.getInstance(defaultEncryptType);
            SecretKey secret = new SecretKeySpec(macKey.getBytes(),HMACSHA256);
            mac.init(secret);
            byte[] doFinal = mac.doFinal(s.getBytes());
            sign = Hex.encodeHexString(doFinal);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sign;
    }
    
    public static void main(String[] args) throws Exception{
        //20cc6689ca24be49a3be2627adabecad6b6177b5c929c9cb955a0630eb72ebe3
        //7c6d09eb13a11f21fbc873b17e0b46307728e839553c5f044010061cae0cd636
//39f62a2db03688a3129e0aa1792fc65fe8d997e7
    	HmacHanlder testOb = new HmacHanlder("123456");
    	String result = testOb.encrypt("Message");
        HmacHanlder testOb2 = new HmacHanlder("456321");
        String result2 = testOb2.encrypt("123456");
    	System.out.println(result);
        System.out.println(result2);
    }
}